<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-people"></i> 用户管理
                </el-breadcrumb-item>
                <el-breadcrumb-item>
                    <i class="el-icon-lx-friend"></i> 管理员用户
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button
                        type="primary"
                        icon="el-icon-delete"
                        class="handle-del mr10"
                        @click="delAllSelection"
                >批量删除
                </el-button>
                <el-input placeholder="输入昵称关键词检索"
                          v-model="search"
                          @clear="getData(1,10)"
                          clearable
                          @keyup.enter.native="handleSearch"
                          class="handle-input mr10">
                </el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            </div>
            <el-table
                    :data="adminUserList"
                    border
                    class="table"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
                    @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="userId" label="ID" width="55" align="center"></el-table-column>
                <el-table-column prop="account" label="用户名" align="center"></el-table-column>
                <el-table-column prop="phone" label="绑定手机号" align="center"></el-table-column>
                <el-table-column prop="nick" label="昵称" align="center"></el-table-column>
                <el-table-column label="用户头像" width="80" align="center">
                    <template slot-scope="scope">
                        <el-image
                                class="table-td-img"
                                :src="scope.row.avatarUrl"
                                :preview-src-list="[scope.row.avatarUrl]"
                        ></el-image>
                    </template>
                </el-table-column>
                <el-table-column label="创建人" width="120">
                    <template slot-scope="scope">
                        {{scope.row.createOne.nick}}
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="170"></el-table-column>
                <el-table-column label="更新者" width="120">
                    <template slot-scope="scope">
                        {{scope.row.updateOne ? scope.row.updateOne.nick : '暂无更新'}}
                    </template>
                </el-table-column>
                <el-table-column label="更新时间" width="170">
                    <template slot-scope="scope">
                        {{scope.row.updateTime ? scope.row.updateTime : '暂无更新'}}
                    </template>
                </el-table-column>
                <el-table-column label="状态" align="center" width="100">
                    <template slot-scope="scope">
                        <el-tag
                                :type="scope.row.status=== 1 ?'success':'danger'"
                        >{{scope.row.status === 1 ? '使用中' : '已禁用'}}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200" align="center" fixed="right">
                    <template slot-scope="scope">
                        <el-button
                                type="text"
                                icon="el-icon-lx-lock"
                                v-show="scope.row.status===1"
                                style="color: darkred; margin-left: 10px"
                                @click="changeState(scope.$index, scope.row)"
                        >禁用
                        </el-button>
                        <el-button
                                type="text"
                                icon="el-icon-lx-unlock"
                                v-show="scope.row.status!==1"
                                style="color: #00a854"
                                @click="changeState(scope.$index, scope.row)"
                        >启用
                        </el-button>
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="handleEdit(scope.$index, scope.row)"
                        >编辑
                        </el-button>
                        <el-button
                                type="text"
                                icon="el-icon-delete"
                                class="red"
                                @click="handleDelete(scope.$index, scope.row)"
                        >删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="addButt">
                <el-button type="primary" icon="el-icon-plus" @click="handleAdd">添加</el-button>
            </div>
            <div class="pagination">
                <el-pagination
                        background
                        layout="total, prev, pager, next"
                        :current-page="current"
                        :page-size="size"
                        :total="total"
                        @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="用户信息编辑" :visible.sync="editVisible" width="30%" center @close="cancelEdit">
            <el-form ref="editForm" :model="form" label-width="100px">
                <div class="editAvatar">
                    <el-image :src="form.avatarUrl" @click="avatarUpload" ></el-image>
                    <input type="file" accept="image/*" class="avatarUpload" v-show="false" @change="setImage"></input>
                </div>
                <el-form-item label="Id">
                    <el-input disabled v-model="form.userId"></el-input>
                </el-form-item>
                <el-form-item label="用户名">
                    <el-input v-model="form.account" disabled></el-input>
                </el-form-item>
                <el-form-item label="手机号">
                    <el-input v-model="form.phone"></el-input>
                </el-form-item>
                <el-form-item required label="昵 称">
                    <el-input v-model="form.nick"></el-input>
                </el-form-item>
                <el-form-item label="账号状态">
                    <el-radio-group v-model="form.status">
                        <el-radio :label="1">启用</el-radio>
                        <el-radio :label="-1">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="上次登录时间">
                    <el-input v-model="form.lastLogin" disabled></el-input>
                </el-form-item>
                <el-form-item label="密 码">
                    <el-button type="danger" :disabled="resetPassword" @click="resetPassword=true">重置密码</el-button>
                    <span v-show="resetPassword">密码已重置！保存后生效！</span>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible=false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">保 存</el-button>
            </span>
        </el-dialog>

        <!-- 添加弹出框 -->
        <el-dialog title="新建管理员用户" :visible.sync="addVisible" width="30%" center @close="cancelAdd">
            <el-form ref="addForm" :model="newForm" label-width="100px">
                <div class="editAvatar">
                    <el-image :src="newForm.avatarUrl" @click="avatarUpload" ></el-image>
                    <input type="file" accept="image/*" class="avatarUpload" v-show="false" @change="setImage"></input>
                </div>
                <el-form-item required label="用户名">
                    <el-input v-model="newForm.account" placeholder="请输入用户名"></el-input>
                </el-form-item>
                <el-form-item required label="昵 称">
                    <el-input v-model="newForm.nick" placeholder="请输入昵称"></el-input>
                </el-form-item>
                <el-form-item required label="密 码">
                    <el-input v-model="newForm.password" placeholder="请输入手机"></el-input>
                </el-form-item>
                <el-form-item label="手机号">
                    <el-input v-model="newForm.phone" placeholder="请输入手机号"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveAdd">添 加</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import { getRequest, postRequest } from '../../api/index';
    import {getTime} from '../../utils/dateTimeUtil';

    export default {
        name: 'AdminUser',
        data() {
            return {
                adminUserList: [],
                multipleSelection: [],
                editVisible: false,
                addVisible: false,
                total: 0,
                size: 0,
                current: 1,
                form: {},
                idx: -1,
                baseUrl: 'http://localhost:8888',
                search: '',
                currentUserId: Number(sessionStorage.getItem('userId')),
                currentUserNick: sessionStorage.getItem('userNick'),
                noAvatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
                resetPassword: false,
                oldForm: {},
                isSave: false,
                uploadImgUrl: '',
                file: null,
                newForm: {
                    account: '',
                    password: '',
                    identity: 1,
                    status: 1,
                    phone: '',
                    nick: '',
                    avatarUrl: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
                    createBy: Number(sessionStorage.getItem('userId')),
                    createTime: ''
                }
            };
        },
        created() {
            this.getData(1, 10);
        },
        inject: ['reload'],
        watch: {
            search(){
                if(this.search===''){
                    this.getData(1, 10);
                }
            }
        },
        methods: {
            getData(current, size) {
                const params = { current: current, size: size };
                getRequest('/getAdminUserList', params).then(resp => {
                    if (resp) {
                        this.total = resp.total;
                        this.current = resp.current;
                        this.size = resp.size;
                        resp.list.forEach(item => {
                            if (item.avatarUrl) {
                                item.avatarUrl = this.baseUrl + item.avatarUrl;
                            }else{
                                item.avatarUrl = this.noAvatar;
                            }
                        });
                        this.adminUserList = resp.list;
                    } else {
                        console.log('获取管理员用户列表失败');
                    }
                });
            },
            // 触发搜索按钮
            handleSearch() {
                if(this.search===''){
                    this.$message('搜索内容不能为空');
                    return false;
                }
                const params={
                    keyword: this.search,
                    current: 1,
                    size: 10
                };
                getRequest('/searchAdminUsers', params).then(resp=>{
                    this.total = resp.total;
                    this.current = resp.current;
                    this.size = resp.size;
                    resp.list.forEach(item=>{
                        if (item.avatarUrl) {
                            item.avatarUrl = this.baseUrl + item.avatarUrl;
                        }else{
                            item.avatarUrl = this.noAvatar;
                        }
                    });
                    this.adminUserList = resp.list;
                });
            },
            // 删除操作
            handleDelete(index, row) {
                // 二次确认删除
                this.$confirm('确定要永久删除 "'+row.nick+'" 这个管理员用户吗？删除后该管理员用户将不能再进入后台系统！！！', '警告', {
                    type: 'error'
                }).then(() => {
                    postRequest('/deleteUser', { userId: row.userId}).then(resp=>{
                        if(resp==='success'){
                            this.$message.error(`管理员用户 ${row.nick} 已永久删除！`);
                            this.adminUserList.splice(index, 1);
                        }
                    })
                });
            },
            // 多选操作
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            delAllSelection() {
                const length = this.multipleSelection.length;
                if(length===0){
                    this.$message("请选择要删除的管理员用户");
                    return false;
                }
                const deleteList = [];
                this.multipleSelection.forEach(item=>{
                    deleteList.push(item.userId);
                });
                this.$confirm('确定要永久删除这 '+length+' 个管理员用户吗？ 删除后这些管理员用户将不能再进入后台系统！！！',
                    '警告',{type: 'error'}).then(()=>{
                    postRequest('/deleteUsers', {deleteList: deleteList}).then(resp=>{
                        if(resp==='success'){
                            this.$message.error(`已永久删除 ${length} 个管理员用户！`);
                            this.multipleSelection = [];
                            this.reload();
                        }
                    })
                })
            },
            changeState(index, row){
                this.idx=index;
                this.form=row;
                if(this.form.status===1){
                    this.form.status=-1;
                }else{
                    this.form.status=1;
                }
                this.form.updateOne={nick: this.currentUserNick};
                const date=new Date();
                this.form.updateTime=getTime(date);
                const params={
                    userId: this.form.userId,
                    status: this.form.status,
                    currentUserId: this.currentUserId,
                    updateTime: date.getTime()
                };
                postRequest('/changeUserStatus', params).then(resp=>{
                    if(resp==='success'){
                        this.form.status===1 ?
                            this.$message.success('已启用该管理员用户！')
                            :
                            this.$message('已禁用该管理员用户！');
                    }else{
                        this.$message.error('操作失败！');
                    }
                });
                this.$set(this.adminUserList, this.idx, this.form);
            },
            // 编辑操作
            handleEdit(index, row) {
                this.idx = index;
                this.form = row;
                this.oldForm = JSON.parse(JSON.stringify(row));
                this.editVisible = true;
            },
            // 保存编辑
            saveEdit() {
                this.$confirm('确定保存对用户 "' + this.form.nick + '" 信息的更改吗？',
                    '警告', { type: 'warning' }).then(async () => {
                    const date=new Date();
                    this.form.updateBy=this.currentUserId;
                    this.form.updateTime=getTime(date);
                    const res= await this.syncRequest();
                    if(res && res.data!==''){
                        this.form.avatarUrl=res.data;
                    }else{
                        this.form.avatarUrl=null;
                    }
                    const params = { user: this.form, resetPassword: this.resetPassword};
                    postRequest('/updateUser', params).then(resp => {
                        this.form.avatarUrl=res ? this.uploadImgUrl : this.oldForm.avatarUrl;
                        if (resp === 'success') {
                            this.editVisible = false;
                            this.resetPassword= false;
                            this.$message.success('保存成功！');
                            this.form.updateOne={nick: this.currentUserNick};
                            this.isSave=true;
                        } else {
                            this.$message.error('操作失败！');
                        }
                    });
                }).catch(() => {
                });
            },
            cancelEdit() {
                if(!this.isSave){
                    this.$set(this.adminUserList, this.idx, this.oldForm);
                }
                this.editVisible = false;
                this.resetPassword = false;
                this.isSave=false;
                this.file=null;
                this.oldForm=null;
            },
            // 分页导航
            handlePageChange(val) {
                this.getData(val, this.size);
            },
            avatarUpload(){
                document.querySelector('.avatarUpload').click();
            },
            setImage(e) {
                const file = e.target.files[0];
                this.file=file;
                if (!file.type.includes('image/')) {
                    this.$message.error('请选择图片文件');
                    return;
                }
                const reader = new FileReader();
                reader.onload = (event) => {
                    this.form.avatarUrl = event.target.result;
                    this.uploadImgUrl=event.target.result;
                    this.newForm.avatarUrl=event.target.result;
                    e.target.value='';
                };
                reader.readAsDataURL(file);
            },
            async syncRequest(){  //同步请求方法，axios默认是异步请求，同步需要使用async和await关键字
                if(this.file===null){
                    return null;
                }
                let formData=new FormData();
                formData.append('img', this.file);
                let res=await this.$axios({
                    method: 'post',
                    url: '/api/saveImageToServer',
                    data: formData
                });
                return res;
            },
            handleAdd(){
                this.oldForm=JSON.parse(JSON.stringify(this.newForm));
                this.addVisible=true;
            },
            cancelAdd(){
                this.newForm=this.oldForm;
                this.oldForm=null;
                this.file=null;
                this.addVisible=false;
            },
            async saveAdd(){
                if(this.newForm.account!=='' && this.newForm.nick!=='' && this.newForm.password!==''){
                   if(!this.file){
                       this.newForm.avatarUrl=null;
                   }else{
                       const res=await this.syncRequest();
                       this.newForm.avatarUrl=res.data;
                   }
                   this.newForm.createTime=getTime(new Date());
                   postRequest('/addUser', this.newForm).then(resp=>{
                       if(resp==='success'){
                           this.$message.success('添加管理员用户成功！');
                           this.addVisible=false;
                           this.reload();
                       }else{
                           this.$message.error('添加失败！');
                       }
                   })
                }else{
                    this.$message.error('未填写必选字段！');
                    return false;
                }
            }
        }
    };
</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }

    .table {
        width: 100%;
        font-size: 14px;
    }
    .table td{
        max-height: 100px;
    }
    .red {
        color: #ff0000;
    }

    .mr10 {
        margin-right: 10px;
    }

    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
    }
    .addButt{
        margin-top: 15px;
    }
    .editAvatar {
        text-align: center;
    }

    .editAvatar .el-image {
        width: 80px;
        margin-bottom: 20px;
    }

    .el-form-item span {
        margin-left: 10px;
        font-size: 10px;
        color: red;
    }
    .crop-demo-btn{
        position: relative;
        width: 100px;
        height: 40px;
        line-height: 40px;
        padding: 0 20px;
        margin-left: 30px;
        background-color: #409eff;
        color: #fff;
        font-size: 14px;
        border-radius: 4px;
        box-sizing: border-box;
    }
    .crop-input{
        position: absolute;
        width: 100px;
        height: 40px;
        left: 0;
        top: 0;
        opacity: 0;
        cursor: pointer;
    }
</style>
